﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LinqToTwitter;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using System.Diagnostics;
using System.Windows.Media.Animation;
using WPF.Extensions;

namespace TwitCast
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private Timeline userTimeline;
		private Timer popupTimer;
        private StatefulStoryboard statefulOne;

		public MainWindow()
		{
			InitializeComponent();

			this.popupTimer = new Timer();
			this.popupTimer.Interval = 10000;
			this.popupTimer.Tick += new EventHandler(popupTimer_Tick);

			try
			{
				this.userTimeline = new Timeline();
				this.userTimeline.NewTweetsAvailable += new EventHandler<EventArgs>(userTimeline_NewTweetsAvailable);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		private delegate void VoidDelegate();

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			// Position the window
			Screen s = Screen.PrimaryScreen;
			int left = (s.WorkingArea.Width / 2) - ((int)this.Width / 2);
			this.Left = left;
			this.Top = 0;

            statefulOne = (StatefulStoryboard)this.Resources["statefulOne"];
            statefulOne.ChangeToInitialState();

			// Start the timeline
			userTimeline.Start();
		}

		private void userTimeline_NewTweetsAvailable(object sender, EventArgs e)
		{
			Dispatcher.Invoke(new VoidDelegate(ShowTweets));
		}

		private void ShowTweets()
		{
            tweetsPresenter.ItemsSource = null;
			tweetsPresenter.ItemsSource = userTimeline.Tweets;

			tweetsViewer.ScrollToEnd();

            if(statefulOne.CurrentState != "AllTweets")
                statefulOne.ChangeToState("NewTweet");

            this.popupTimer.Start();
		}

		private void popupTimer_Tick(object sender, EventArgs e)
		{
			this.popupTimer.Stop();

			Dispatcher.Invoke(new VoidDelegate(HideWindow));
		}

		private void HideWindow()
		{
            if (statefulOne.CurrentState == "NewTweet")
                statefulOne.ChangeToInitialState();
		}

        private void tweetWindow_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            statefulOne.ChangeToState("AllTweets");
        }

        private void tweetWindow_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            statefulOne.ChangeToInitialState();
        }
	}
}
